﻿/**
 * 公共js
 */
if (typeof (type) == 'undefined' || type == null) {

    /**
     * 1.判断上下文类型
     * content 内容脚本,与页面交互
     * popup 用户点击插件图标后显示的小窗口页面
     * background 处理后台任务
     */
    var type = null;
    if (window.location.protocol.indexOf("http") >= 0) {
        type = 'content';
    } else if (window.location.protocol == 'chrome-extension:' && window.location.href.indexOf('background') >= 0) {
        type = 'background';
    } else if (window.location.protocol == 'chrome-extension:' && window.location.href.indexOf('popup') >= 0) {
        type = 'popup';
    }

    //设置请求端同步返回还是异步返回
    var sync = true;//true 同步 false 异步

    var CommonResponse = {
        'ok': function (data) {
            return {'success': true, 'code': 0, 'data': data};
        }
    };

    var requestMap = {
        hello: function (args, sender, sendResponse) {
            console.log(type + ": hello " + args);
            sendResponse(CommonResponse.ok(type + ": hello " + args));
        },
        post: function (args, sender, sendResponse) {
            window.$.post(args['url'], args['params'], function (result) {
                sendResponse(CommonResponse.ok(JSON.stringify(result)));
            });
        },
        isSSL: function () {
            var ssl = window.origin.indexOf("https") >= 0;
            return ssl;
        },
        getUrl: function (args, sender, sendResponse) {
            sendResponse(CommonResponse.ok(window.location.href));
        },
        eval: function (args, sender, sendResponse) {
            sendResponse(CommonResponse.ok(eval(args['command'])));
        },
        isSSL: function (args, sender, sendResponse) {
            sendResponse(CommonResponse.ok(eval(args['command'])));
        },
        getRootPath: function (args, sender, sendResponse) {
            sendResponse(CommonResponse.ok(chrome.runtime.getURL("")));
            return sync;
        },
        //导入插件内的js
        importJsFromLocal: function (args, sender, sendResponse) {
            var path = args['path'];
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = chrome.runtime.getURL(path);
            (document.head || document.documentElement).appendChild(script);
            return sync;
        },
        //从web引入页面js
        importJsFromWeb: function (args, sender, sendResponse) {
            var path = args['path'];
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = (window.origin.indexOf("https") >= 0 ? "https://" : "http://") + path;
            (document.head || document.documentElement).appendChild(script);
            return sync;
        },
        //通过js源码引入js
        importJsByJsCodeString: function (args, sender, sendResponse) {
            var jsCode = args['jsCode'];
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.innerHTML = jsCode;
            (window.document.head || window.document.documentElement).appendChild(script);
            return sync;
        }

    };

    var handler = {
        onAuthRequired: [],
        onBeforeRedirect: [],
        onBeforeSendHeaders: [],
        onSendHeaders: [],
        onHeadersReceived: [],
        onResponseStarted: [],
        onCompleted: [],
        onBeforeRequest: [],
        onErrorOccurred: []
    };

    //请求background的服务
    function requestBackground(requestMapping, args, callback) {//popup 访问 background
        var request = {'requestMapping': requestMapping, 'args': args};
        chrome.runtime.sendMessage(request, function (response) {
            if (null != callback && 'undefined' != typeof (callback)) {
                callback(response);
            }
        });
        return sync;
    }

    //请求content_script的服务
    function requestContent(requestMapping, args, callback) {
        chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
            var request = {requestMapping, args};
            if (tabs != null && tabs.length != 0) {
                chrome.tabs.sendMessage(tabs[0].id, request, callback);
            }
        });
        return sync;
    }

    //background和content_script开启服务监听
    if (type == 'background' || type == 'content') {
        chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
            var requestMapping = req['requestMapping'];
            if (requestMapping != null && typeof (requestMapping) != 'undefined') {
                var args = req['args'];
                var result = requestMap[requestMapping].call(this, args, sender, sendResponse);
            }
            return sync;
        });
    }

    if (type == 'content') {
        //接收页面消息 window.postMessage
        window.addEventListener("message", function (req, sender, sendResponse) {
            var requestMapping = req['data']['requestMapping'];
            if (requestMapping != null && typeof (requestMapping) != 'undefined') {
                var args = req['data']['args'];
                return requestMap[requestMapping].call(this, args, sender, sendResponse);
            }
            return sync;
        }, false);
        // chrome.extension.sendRequest
        chrome.extension.onRequest.addListener(function (req, sender, sendResponse) {
            var requestMapping = req['requestMapping'];
            if (requestMapping != null && typeof (requestMapping) != 'undefined') {
                var args = req['args'];
                requestMap[requestMapping].call(this, args, sender, sendResponse);
            }
            return sync;
        });
    }

    if (type == 'background') {
        //监听事件
        chrome.webRequest.onResponseStarted.addListener(function (details) {
            for (var i = 0; i < handler['onResponseStarted'].length; i++) {
                var cur = handler['onResponseStarted'][i];
                if (cur.match(details)) {
                    cur.execute(details);
                }
            }
            return sync;
        }, {urls: ["<all_urls>"]});
        //监听事件
        chrome.webRequest.onCompleted.addListener(function (details) {
            for (var i = 0; i < handler['onCompleted'].length; i++) {
                var cur = handler['onCompleted'][i];
                if (cur.match(details)) {
                    cur.execute(details);
                }
            }
            return sync;
        }, {urls: ["<all_urls>"]});
        //监听事件
        chrome.webRequest.onHeadersReceived.addListener(function (details) {
            var hasMatch = false;
            for (var i = 0; i < handler['onHeadersReceived'].length; i++) {
                var cur = handler['onHeadersReceived'][i];
                if (cur.match(details)) {
                    hasMatch = true;
                    cur.execute(details);
                }
            }
            return {responseHeaders: details.responseHeaders};
        }, {urls: ["<all_urls>"], types: ["main_frame", "sub_frame"]}, ["responseHeaders", "blocking"]);

        // 监听页面请求的请求头
        chrome.webRequest.onBeforeSendHeaders.addListener(
            function (details) {
                for (var i = 0; i < handler['onBeforeSendHeaders'].length; i++) {
                    var cur = handler['onBeforeSendHeaders'][i];
                    if (cur.match(details)) {
                        hasMatch = true;
                        cur.execute(details);
                    }
                }
                return {requestHeaders: details.requestHeaders};
            },
            {
                urls: ["<all_urls>"], // 匹配所有 URL
                types: ["main_frame", "sub_frame", "xmlhttprequest"]
            },
            ["blocking"]
        );

        //监听事件
        chrome.webRequest.onBeforeRequest.addListener(function (details) {
            var oldUrl = details.url;
            var hasMatch = false;
            for (var i = 0; i < handler['onBeforeRequest'].length; i++) {
                var cur = handler['onBeforeRequest'][i];
                if (cur.match(details)) {
                    hasMatch = true;
                    cur.execute(details);
                }
            }
            if (oldUrl == details.url) {

            } else {
                return {
                    redirectUrl: details.url
                };
            }
        }, {
            "urls": ["http://*/*", "https://*/*"],
            "types": [
                "main_frame",
                "sub_frame",
                "stylesheet",
                "script",
                "image",
                "object",
                "xmlhttprequest",
                "other"
            ]
        }, ["blocking"]);

    }

}
